package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONException;
import org.json.JSONObject;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class ContactAvatarAddActivity extends AppCompatActivity {

    private final static int CONTACT_AVATAR_ADD_CODE = 100;

    private App mApp;

    private ImageView imageViewBack;

    private ImageView rhino;
    private ImageView girafe;
    private ImageView bird;
    private ImageView dolphin;
    private ImageView elephant;
    private ImageView car;
    private ImageView train;
    private ImageView plane;
    private ImageView ship;
    private ImageView bike;
    private ImageView sweet;
    private ImageView icecream;
    private ImageView candy;
    private ImageView chocolate;
    private ImageView cupcake;
    private ImageView male1;
    private ImageView female1;
    private ImageView male2;
    private ImageView female2;
    private ImageView male3;
    private ImageView female3;
    private ImageView male4;
    private ImageView female4;
    private ImageView home;
    private ImageView school;
    private ImageView office;
    private ImageView default0;

    public ParentBleTransfer mParentBleTransfer;

    private KidInfoEntity mKidInfoEntity;

    private DealWithWaitingDlg mDealWithWaitingDlg;

    private boolean mScreenOperate = false;

    private boolean mUnReceiver = true;

    private static final String TAG = "TAG";
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "ContactAvatarAddActivity_onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_avatar_add);
        mApp = (App)getApplication();
        mounted();
        initListener();
        initReceiver();
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "ContactAvatarAddActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    public void onBackPressed() {
        backToContactAddActivity();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "ContactAvatarAddActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if ((mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT)&&(!mEditReopening)) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(ContactAvatarAddActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mEditReopening = true;
                    sendIsUsingToKid();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                }
                mSystemHomeFlag = false;
            }
        }

    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ContactAvatarAddActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ContactAvatarAddActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }


    private void mounted() {
        Log.i(TAG, "ContactAvatarAddActivity_mounted");
        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        imageViewBack = (ImageView) findViewById(R.id.imageViewBack);
        rhino = (ImageView) findViewById(R.id.rhino);
        girafe = (ImageView) findViewById(R.id.girafe);
        bird = (ImageView) findViewById(R.id.bird);
        dolphin = (ImageView) findViewById(R.id.dolphin);
        elephant = (ImageView) findViewById(R.id.elephant);
        car = (ImageView) findViewById(R.id.car);
        train = (ImageView) findViewById(R.id.train);
        plane = (ImageView) findViewById(R.id.plane);
        ship = (ImageView) findViewById(R.id.ship);
        bike = (ImageView) findViewById(R.id.bike);
        sweet = (ImageView) findViewById(R.id.sweet);
        icecream = (ImageView) findViewById(R.id.icecream);
        candy = (ImageView) findViewById(R.id.candy);
        chocolate = (ImageView) findViewById(R.id.chocolate);
        cupcake = (ImageView) findViewById(R.id.cupcake);
        male1 = (ImageView) findViewById(R.id.male1);
        female1 = (ImageView) findViewById(R.id.female1);
        male2 = (ImageView) findViewById(R.id.male2);
        female2 = (ImageView) findViewById(R.id.female2);
        male3 = (ImageView) findViewById(R.id.male3);
        female3 = (ImageView) findViewById(R.id.female3);
        male4 = (ImageView) findViewById(R.id.male4);
        female4 = (ImageView) findViewById(R.id.female4);
        home = (ImageView) findViewById(R.id.home);
        school = (ImageView) findViewById(R.id.school);
        office = (ImageView) findViewById(R.id.office);
        default0 = (ImageView) findViewById(R.id.default0);
    }


    private void initListener() {
        Log.i(TAG, "ContactAvatarAddActivity_initListener");
        //imageViewBack
        imageViewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                backToContactAddActivity();
            }
        });


        rhino.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("1");
            }
        });

        girafe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("2");
            }
        });

        bird.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("3");
            }
        });
        dolphin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("4");
            }
        });
        elephant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("5");
            }
        });

        car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("6");
            }
        });

        train.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("7");
            }
        });

        plane.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("8");
            }
        });

        ship.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("9");
            }
        });
        bike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("10");
            }
        });

        sweet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("11");
            }
        });

        icecream.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("12");
            }
        });
        candy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("13");
            }
        });
        chocolate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("14");
            }
        });
        cupcake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("15");
            }
        });
        male1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("16");
            }
        });
        female1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("17");
            }
        });
        male2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("18");
            }
        });
        female2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("19");
            }
        });
        male3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("20");
            }
        });
        female3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("21");
            }
        });
        male4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("22");
            }
        });
        female4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("23");
            }
        });
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("24");
            }
        });
        school.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("25");
            }
        });
        office.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("26");
            }
        });
        default0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToContactAddActivity("0");
            }
        });

    }
    private void backToContactAddActivity() {
        Log.i(TAG, "ContactAvatarAddActivity_backToContactAddActivity");
        mPageJumpFlag = true;
        Intent intent = getIntent();
        setResult(CONTACT_AVATAR_ADD_CODE, intent);
        finish();
    }
    private void goToContactAddActivity(String index) {
        Log.i(TAG, "ContactAvatarAddActivity_goToContactAddActivity");
        mPageJumpFlag = true;
        Intent intent = getIntent();
        setResult(CONTACT_AVATAR_ADD_CODE, intent);
        intent.putExtra("imageIndex", index);
        finish();
    }

    private void initReceiver(){
        Log.i(TAG, "ContactAvatarAddActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // Bluetooth
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        //isFinish
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }


    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    Log.i(TAG, "ContactAvatarAddActivity_systemReceiver_ACTION_SCREEN_OFF");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    Log.i(TAG, "ContactAvatarAddActivity_systemReceiver_ACTION_USER_PRESENT");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            String message = "編集を再開しています...";
                            mDealWithWaitingDlg = new DealWithWaitingDlg(ContactAvatarAddActivity.this, R.style.commonDlg, message, false);
                            mDealWithWaitingDlg.show();
                            mScreenOperate = true;
                            mEditReopening = true;
                            sendIsUsingToKid();
                            // ブロードキャストの再登録
                            unregisterReceiver(systemReceiver);
                            initReceiver();
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    Log.i(TAG, "ContactAvatarAddActivity_systemReceiver_ACTION_CLOSE_SYSTEM_DIALOGS");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                }else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    Log.i(TAG, "ContactAvatarAddActivity_receiver_RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED");
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (((App)getApplication()).isMimamoriCheck(macAddress)) {
                        ((App)getApplication()).addmLsIsMimamori(macAddress);
                        sendExitToKid();
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(ContactAvatarAddActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        ((App)getApplication()).updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactAvatarAddActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(ContactAvatarAddActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                Log.i(TAG, "ContactAvatarAddActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED");
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                try {
                    JSONObject resp = new JSONObject(bluetoothReceiverDto.getRetStr());
                    String method = resp.getString("method");

                    if (null != method) {
                        if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(method)) {
                            JSONObject data = resp.getJSONObject("data");
                            Log.i(TAG, "ContactAvatarAddActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_getOperatingState:"+data);
                            if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                                //发送enter
                                sendEnterToKid();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactAvatarAddActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                        // ページジャンプ
                                        mPageJumpFlag = true;
                                        ContactAvatarAddActivity.this.finish();
                                    }
                                });
                            }
                        }else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(method)){
                            Log.i(TAG, "ContactAvatarAddActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_onOperateInterrupt");
                            String message = "キッズケータイが操作されました。編集を中断します。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactAvatarAddActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    backToEditActivity();
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                     Log.e(TAG,e.getMessage());
                }

            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                //isFinish
                Log.i(TAG, "ContactAvatarAddActivity_receiver_RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED");
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    if (!mScreenOperate) {

                    } else {
                        mScreenOperate = false;
                        mEditReopening = false;
                        handler.sendEmptyMessage(0);
                    }
                }

            }
        }
    };

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
        }
    };

    /**
     * enter
     */
    public void sendEnterToKid() {
        Log.i(TAG, "ContactAvatarAddActivity_sendEnterToKid");
        try {
            new BusinessThread(Constants.SEND_KID_ENTER,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    null,
                    PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
        } catch (Exception e) {
             Log.e(TAG,e.getMessage());
        }
    }

    /**
     * is using
     */
    public void sendIsUsingToKid() {
        Log.i(TAG, "ContactAvatarAddActivity_sendIsUsingToKid");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", "getOperatingState");
            jsonObject.put("data", JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
        } catch (JSONException e) {
             Log.e(TAG,e.getMessage());
        } catch (Exception e) {
             Log.e(TAG,e.getMessage());
        }
    }

    private void backToEditActivity() {
        Log.i(TAG, "ContactAvatarAddActivity_backToEditActivity");
        mPageJumpFlag = true;
        Intent intent = new Intent();
        intent.setClass(this, EditActivity.class);
        startActivity(intent);
    }

    /**
     * exit
     */
    public void sendExitToKid(){
        Log.i(TAG, "ContactAvatarAddActivity_sendExitToKid");
        new BusinessThread(Constants.SEND_KID_EXIT,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
    }
}
